﻿#region Copyright Notice
// 
// 
//  
//  Copyright (c) 2009-2011 Anindya Chatterjee
//  
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  
//      http://www.apache.org/licenses/LICENSE-2.0
//  
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// 
// 
#endregion
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using AbstractClass.Runtime.Serialization;

namespace AbstractClass.Extensions
{
    /// <summary>
    /// Provides a set of extension methods for <see cref="object"/>.
    /// </summary>
    public static class ObjectExtensions
    {
        /// <summary>
        /// Casts an object of anonymous type <typeparamref name="TSource"/> to an object of
        /// another anonymous type <typeparamref name="TExample"/> using its example.
        /// </summary>
        /// <typeparam name="TExample">The type of the example.</typeparam>
        /// <typeparam name="TSource">The type of the source.</typeparam>
        /// <param name="obj">The object of anonymous type <typeparamref name="TSource"/>.</param>
        /// <param name="example">The example of anonymous type <typeparamref name="TExample"/>.</param>
        /// <returns>
        /// An object of anonymous type <typeparamref name="TExample"/>.
        /// </returns>
        /// <exception cref="InvalidCastException"><paramref name="obj"/> and <paramref name="example"/> have different signature.</exception>
        public static TExample CastByExample<TExample, TSource>(this TSource obj, TExample example)
            where TExample : class
            where TSource : class
        {
            if (obj is TExample)
                return obj.CastTo<TSource, TExample>();
            throw new InvalidCastException();
        }

        /// <summary>
        /// Throws an <see cref="ArgumentNullException"/> if <paramref name="checkedObject"/> is <c>null</c>.
        /// </summary>
        /// <typeparam name="T">The type of the object to check for <c>null</c>.</typeparam>
        /// <param name="checkedObject">The object to check for <c>null</c>.</param>
        public static void ThrowIfNull<T>(this T checkedObject) where T : class
        {
            if (checkedObject == null)
                throw new ArgumentNullException();
        }

        /// <summary>
        /// Throws an <see cref="ArgumentNullException"/> if <paramref name="checkedObject"/> is <c>null</c>.
        /// </summary>
        /// <typeparam name="T">The type of the object to check for <c>null</c>.</typeparam>
        /// <param name="checkedObject">The object to check for <c>null</c>.</param>
        /// <param name="paramName">The name of the parameter that caused the exception.</param>
        public static void ThrowIfNull<T>(this T checkedObject, string paramName) where T : class
        {
            if (checkedObject == null)
                throw new ArgumentNullException(paramName);
        }

        /// <summary>
        /// Casts from an object of type <typeparamref name="TSource"/> to an object 
        /// of type <typeparamref name="TResult"/>.
        /// </summary>
        /// <param name="value">An object of type <typeparamref name="TSource"/>.</param>
        /// <returns>
        /// An object of type <typeparamref name="TResult"/> if casting successful; otherwise, a <c>default</c> 
        /// value of type <typeparamref name="TResult"/>.
        /// </returns>
        public static TResult CastTo<TSource, TResult>(this TSource value)
        {
            if (value.GetType().GetInterfaces().Contains(typeof (IConvertible)))
            {
                object val = Convert.ChangeType(value, typeof (TResult));
                return (TResult) val;
            }
            if (value is TResult || value.GetType().IsCastableTo(typeof (TResult)))
            {
                return (TResult) (value as Object);
            }
            return default(TResult);
        }


        /// <summary>
        /// Determines whether an object of type <typeparamref name="TSource"/> can be cast to
        /// an object of type <typeparamref name="TResult"/>.
        /// </summary>
        /// <param name="obj">A object of type <typeparamref name="TSource"/>.</param>
        /// <returns>
        /// <c>true</c> if casting is possible; otherwise, <c>false</c>.
        /// </returns>
        public static bool CanCastTo<TSource, TResult>(this TSource obj)
        {
            return obj.GetType().IsCastableTo(typeof (TResult));
        }

        /// <summary>
        /// Creates a deep clone of <paramref name="obj"/>.
        /// </summary>
        /// <typeparam name="T">The type of the object to clone.</typeparam>
        /// <param name="obj">The object to clone.</param>
        /// <returns>A cloned object of type <typeparamref name="T"/>.</returns>
        public static T DeepClone<T>(this T obj)
        {
            var formatter = new BinaryFormatter {SurrogateSelector = new SurrogateSelector()};
            formatter.SurrogateSelector.ChainSelector(
                new NonSerialiazableTypeSurrogateSelector());
            var ms = new MemoryStream();
            formatter.Serialize(ms, obj);
            ms.Position = 0;
            return (T) formatter.Deserialize(ms);
        }
    }
}